import React, { Component } from 'react'
import { Modal, Row, Col, Select } from 'antd'
import PropTypes from 'prop-types'
import style from './NextOperatorSelector.module.less'

const { Option } = Select

export default class NextOperatorSelector extends Component {
  state = {
    operators: [],
    current: ''
  }

  handleOk () {
    this.props.changeOperatorId(this.state.current)
    this.props.hide()
  }

  handleCancel () {
    this.props.hide()
  }

  // 初始化操作者列表和默认操作者
  initOperators () {
    const { list } = this.props
    this.setState({
      operators: list
    })
    if (list.length) {
      this.setState({
        current: list[0].id
      })
    }
  }

  componentDidUpdate (prev) {
    if ((this.props.visible && prev.visible !== this.props.visible) || this.props.list !== prev.list) {
      this.initOperators()
    }
  }

  componentDidMount () {
    this.initOperators()
  }

  // 渲染人员列表
  renderOptions () {
    return this.state.operators.map(li => (
      <Option key={li.id} value={li.id}>{li.name}</Option>
    ))
  }

  render () {
    return (
      <Modal
        title='选择审批人'
        maskClosable={false}
        open={this.props.visible}
        onOk={() => this.handleOk()}
        onCancel={() => this.handleCancel()}
      >
        <Row>
          <Col span={4}><div className={style.label}>审批人：</div></Col>
          <Col span={20}>
            <Select className={style.full} defaultValue='lucy' value={this.state.current} onChange={v => this.setState({ current: v })}>
              {this.renderOptions()}
            </Select>
          </Col>
        </Row>
      </Modal>
    )
  }
}

NextOperatorSelector.propTypes = {
  visible: PropTypes.bool,
  list: PropTypes.array,
  hide: PropTypes.func,
  changeOperatorId: PropTypes.func
}

NextOperatorSelector.defaultProps = {
  visible: false,
  list: [],
  hide: () => {},
  changeOperatorId: () => {}
}
